package com.darker.secking.rabbitmq;

import com.darker.secking.entity.Order;
import com.darker.secking.entity.SeckillMessage;
import com.darker.secking.entity.SeckingOrder;
import com.darker.secking.entity.User;
import com.darker.secking.service.IGoodsService;
import com.darker.secking.service.IOrderService;
import com.darker.secking.utils.JsonUtil;
import com.darker.secking.vo.GoodsVo;
import com.darker.secking.vo.LoginVo;
import com.darker.secking.vo.RespBean;
import com.darker.secking.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {
    @Autowired
    IGoodsService goodsService;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IOrderService orderService;


    @RabbitListener(queues = "seckillQueue")
    public void ReceiverMes(String seckillMessageJSON) {
        //将JSON字符串序列化成对象
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(seckillMessageJSON, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodsId = seckillMessage.getGoodsId();
        GoodsVo goods = goodsService.findGoodsById(goodsId);
        //判断库存是否足够
        if (goods.getStockCount() < 1) {
            return;
        }
        //判断是否重复秒杀
        SeckingOrder seckingOrder = (SeckingOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goods.getId());

//        如果有则返回重复秒杀的信息
        if (seckingOrder != null) {
            return;
        }
//        进行创建订单操作
        orderService.secking(user, goods);


    }
}
